<?php

require_once 'vendor/mustangostang/spyc/Spyc.php';
$feedYml = Spyc::YAMLLoad('feed.yml');

$formats = ['atom', 'json'];
$format = 'atom';
if (isset($_REQUEST['format']))
    $format = $_REQUEST['format'];
if (!in_array($format, $formats))
    $format = 'atom';

if ($format == 'atom') {
    header('Content-Type: application/atom+xml; charset=utf-8');
    echo '<?xml version="1.1" encoding="utf-8"?>
';
    echo '<feed xmlns="http://www.w3.org/2005/Atom">
';
    echo "\t<title>$feedYml[title]</title>\n";
    echo "\t<subtitle>$feedYml[subtitle]</subtitle>\n";
    echo "\t<id>urn:uuid:$feedYml[id]</id>\n";
    echo "\t<author>\n\t\t<name>{$feedYml['author']['name']}</name>\n\t\t<uri>{$feedYml['author']['uri']}</uri>\n\t</author>\n";
    echo "\t<icon>$feedYml[icon]</icon>\n";
    echo "\t<logo>$feedYml[logo]</logo>\n";
    echo "\t<link rel=\"self\" type=\"application/atom+xml\" href=\"$feedYml[self]\" />\n";
    echo "\t<link rel=\"alternate\" type=\"text/html\" href=\"$feedYml[website]\" />\n";
    echo "\t<rights>$feedYml[rights]</rights>\n";

    foreach ($feedYml['entries'] as $entry) {
        echo "\t<entry>\n";
        echo "\t\t<title>$entry[title]</title>\n";
        echo "\t\t<id>$entry[id]</id>\n";
        echo "\t\t<updated>$entry[updated]</updated>\n";
        foreach ($entry['categories'] as $category) {
            echo "\t\t<category>\n\t\t\t<term>$category</term>\n\t\t\t<label>" . ucfirst($category) . "</label>\n\t\t</category>\n";
        }
        echo "\t\t<content type=\"xhtml\" xmlns:xhtml=\"http://www.w3.org/1999/xhtml\">\n\t\t\t<xhtml:div>\n$entry[content]\n\t\t\t</xhtml:div>\n\t\t</content>\n";
        echo "\t</entry>\n";
    }

    echo '</feed>';
} else if ($format == 'json') {
    header('Content-Type: application/json; charset=utf-8');
    $feedJson = [
        'version' => 'https://jsonfeed.org/version/1',
        'title' => $feedYml['title'],
        'home_page_url' => $feedYml['website'],
        'feed_url' => $feedYml['self'],
        'description' => $feedYml['subtitle'],
        'icon' => $feedYml['logo'],
        'favicon' => $feedYml['icon'],
        'author' => [
            'name' => $feedYml['author']['name'],
            'url' => $feedYml['author']['uri']
        ],
        'items' => []
    ];
    foreach ($feedYml['entries'] as $entry) {
        array_push($feedJson['items'], [
            'id' => $entry['id'],
            'title' => $entry['title'],
            'content_html' => $entry['content'],
            'date_modified' => $entry['updated'],
            'tags' => $entry['categories']
        ]);
    }
    echo json_encode($feedJson);
}

?>
